/*
* 四川生学教育科技有限公司
* Copyright (c) 2015-2025 Founder Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Founder. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the agreements
* you entered into with Founder.
*
*/
package cn.demo.zookeeper.otherDemo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * @author WUANG (wa@sxw.cn)
 * @description https://my.oschina.net/yafeiok/blog/618835#h3_22
 * @date 2018/11/1 14:46
 * @slogon 站在巨人的肩膀上
 * @since 2.0.0
 */
public class zkConfigServer implements Watcher {
    ZooKeeper zkServer = null;
    String zkNode;

    zkConfigServer(String zkServer, String zkNode, int zkTimeout) {
        this.zkNode = zkNode;
        try {
            this.zkServer = new ZooKeeper(zkServer, zkTimeout, this);
            Stat st = this.zkServer.exists(zkNode, true);
            if (st == null) {
                this.zkServer.create(zkNode, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (IOException e) {
            e.printStackTrace();
            this.zkServer = null;
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void updateConfig(String str) {
        try {
            Stat s = this.zkServer.exists(this.zkNode, true);
            this.zkServer.setData(this.zkNode, str.getBytes(), s.getVersion());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println(event.toString());
        try {
            this.zkServer.exists(zkNode, true);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        zkConfigServer configServer = new zkConfigServer("120.78.169.174:2181", "/username", 2000);
        configServer.updateConfig("haha3");
    }
}